/* eslint-disable react/jsx-indent */
/* eslint-disable import/order */
/* eslint-disable import/no-extraneous-dependencies */
import React, { Component, Fragment } from 'react';
import { DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Tabs, Dropdown, Modal, Menu, Divider, message } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import queryString from 'query-string';
import { connect } from 'dva';
import moment from 'moment';
import Link from 'umi/link';
import router from 'umi/router';
import RebateTmp from './RebateTmp';
import UpdateModal from './UpdateModal';
import styles from '@/utils/utils.less';
import { checkPermissions } from '@/utils/authority';
import judegAuthority from '../../SocialManage/judgeAuthority';

const { TabPane } = Tabs;
@connect(({ rebate, publicdata, loading }) => ({
  rebate,
  publicdata,
  activeKey: rebate.activeKey,
  loading: loading.models.rebate,
}))
@Form.create()
class Rebate extends Component {
  constructor(props) {
    super(props);
    this.state = {
      updateVisible: false,
      selectedRows: [],
      serTypeId: '',
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink) {
      dispatch({
        type: 'rebate/updateModelData',
        payload: {
          activeKey: '1',
        },
      });
    }
    this.getServiceDicList(1);
  }

  // 获取服务类型列表
  getServiceDicList = type => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rebate/fetchServiceDictList',
      payload: {
        serType: type,
      },
    });
  };

  getList = (RefundInfoVo, pagerArg) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rebate/fetchInsList',
      payload: {
        insRefundInfoVo: RefundInfoVo,
        pagerArg,
      },
    });
  };

  clearSelect = () => {
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
  };

  showModal = () => {};

  updateHandleOk = value => {
    const { dispatch, activeKey } = this.props;
    const { refundInfoId, serTypeId, vno } = this.state;
    dispatch({
      type: Number(activeKey) === 1 ? 'rebate/UpdateInsInfo' : 'rebate/UpdateAccuInfo',
      payload: { refundInfoId, serTypeId, ...value, vno },
      callback: response => {
        if (response.success) {
          message.success('操作成功！');
          // this.toggleVoidModal(false);
          this.toggleUpdateModal(false);
          this.child.getList(activeKey);
        } else {
          message.warning(response.message);
        }
      },
    });
  };

  toggleUpdateModal = visible => {
    this.setState({
      updateVisible: visible,
    });
  };

  showUpdateModal = record => {
    const {
      location: { pathname },
    } = this.props;
    const currentPath = pathname.split('/')[1];
    // source=1 线上 source=2 线下
    const { dispatch, activeKey } = this.props;
    // const { type } = this.state;
    const { refundInfoId, serTypeId, vno } = record;
    if (Number(record.state) === 1 || Number(record.state) === 3) {
      if (Number(record.source) === 1) {
        this.setState({
          updateVisible: true,
          refundInfoId,
          serTypeId,
          vno,
        });
        dispatch({
          type:
            Number(activeKey) === 1 ? 'rebate/fetchInsUpdateInfo' : 'rebate/fetchAccuUpdateInfo',
          payload: {
            refundInfoId,
          },
        });
      } else {
        router.push(
          `/${currentPath}/rebate/update?type=${activeKey}&&refundInfoId=${refundInfoId}`
        );
      }
    } else {
      message.warning('已认领、待支付、已支付不可修改线上和线下的返款数据');
    }
  };

  showCancelModal = () => {
    this.setState({
      cancelVoidVisible: true,
    });
  };

  toggleCancelVoidModal = visible => {
    this.setState({
      cancelVoidVisible: visible,
    });
  };

  showVoidModal = record => {
    this.setState({
      refundInfoId: record.refundInfoId,
    });
    Modal.confirm({
      title: '确定要作废当前数据吗？',
      icon: <ExclamationCircleOutlined />,
      content: '作废后将不能取消作废',
      okText: '确定',
      cancelText: '取消',
      onOk: this.voidHandleOk,
      onCancel: () => {},
    });
  };

  showCancelVoidModal = (visible, record) => {
    this.setState({
      cancelVoidVisible: visible,
      refundInfoId: record.refundInfoId,
    });
  };

  voidHandleOk = () => {
    const { dispatch, activeKey } = this.props;
    const { refundInfoId } = this.state;
    dispatch({
      type: Number(activeKey) === 1 ? 'rebate/execInvalidInsInfo' : 'rebate/execInvalidAccuInfo',
      payload: { refundInfoId },
      callback: response => {
        if (response.success) {
          message.success('操作成功！');
          this.child.getList(activeKey);
        } else {
          message.warning('操作失败！');
        }
      },
    });
  };

  cancelVoidHandleOk = () => {
    const { dispatch, activeKey } = this.props;
    const { refundInfoId } = this.state;
    dispatch({
      type:
        Number(activeKey) === 1 ? 'rebate/cancelInvalidInsInfo' : 'rebate/cancelInvalidAccuInfo',
      payload: { refundInfoId },
      callback: response => {
        if (response.success) {
          message.success('操作成功！');
          this.toggleCancelVoidModal(false);
          this.child.getList(activeKey);
        } else {
          message.warning('操作失败！');
        }
      },
    });
  };

  menuDealEs = record => (
    <Menu>
      {checkPermissions('business:insRefundInfo:updateInsRefundInfo') && (
        <Menu.Item>
          <a onClick={() => this.showUpdateModal(record)}>修改</a>
        </Menu.Item>
      )}
      {checkPermissions('business:insRefundInfo:execInvalidInsRefundInfo') && (
        <Menu.Item>
          <a onClick={() => this.showVoidModal(record)}>作废</a>
        </Menu.Item>
      )}
    </Menu>
  );

  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({
      selectedRowKeys,
      selectedRows,
    });
  };

  renderMore = record => {
    const { location } = this.props;
    const authority = judegAuthority(location);
    if (authority === 'socaccmanagesend') {
      return null;
    }
    switch (record.state) {
      case 1:
        return checkPermissions('business:insRefundInfo:updateInsRefundInfo') &&
          checkPermissions('business:insRefundInfo:updateInsRefundInfo') ? (
          <Fragment>
            <Divider type="vertical" />
            <Dropdown overlay={this.menuDealEs(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </Fragment>
        ) : (
          (checkPermissions('business:insRefundInfo:updateInsRefundInfo') && (
            <Fragment>
              <Divider type="vertical" />
              <Menu.Item>
                <a onClick={() => this.showUpdateModal(record)}>修改</a>
              </Menu.Item>
            </Fragment>
          ),
          checkPermissions('business:insRefundInfo:execInvalidInsRefundInfo') && (
            <Fragment>
              <Divider type="vertical" />
              <Menu.Item>
                <a onClick={() => this.showVoidModal(record)}>作废</a>
              </Menu.Item>
            </Fragment>
          ))
        );
      case 2:
        return null;
      case 3:
        return null;
      default:
        return null;
    }
  };

  onRef = ref => {
    this.child = ref;
  };

  onRef1 = ref => {
    this.child1 = ref;
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, dispatch } = this.props;
    dispatch({
      type: 'rebate/updatePagination',
      payload: {
        current: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
    this.child.getList(activeKey, pagination.current, pagination.pageSize, undefined, false);
  };

  tabChange = value => {
    const {
      location: { pathname },
      dispatch,
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    router.push({
      pathname: `${tempUrl}/index`,
    });
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
    dispatch({
      type: 'rebate/updateModelData',
      payload: {
        activeKey: value,
      },
    });
    this.getServiceDicList(value);
    this.resetAndGeLlist(value);
  };

  async resetAndGeLlist(value) {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'rebate/updateModelData',
      payload: {
        expandForm: false,
      },
    });
    await this.child.handleFormReset();
    await this.child1.handleFormReset();
    form.resetFields();
    await this.child.getList(value);
  }

  render() {
    const {
      location: { pathname },
    } = this.props;
    const tempUrl = pathname.split('/index')[0];
    const {
      rebate: { pageData, accuData, serviceDictList, insUpdateVo, accuUpdateVo },
      loading,
      location,
      activeKey,
    } = this.props;
    const { selectedRows, selectedRowKeys, updateVisible, cancelVoidVisible } = this.state;
    const insColumns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeIdName',
        render: text => (text && text) || '--',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '返款金额',
        dataIndex: 'refundAmt',
        onCell: () => ({
          style: {
            textAlign: 'right',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'right',
          },
        }),
      },

      {
        title: '状态',
        dataIndex: 'stateName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      {
        title: '来源',
        dataIndex: 'sourceName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      {
        title: '所属客服',
        dataIndex: 'blngCs',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      // {
      //   title: '所属客服',
      //   dataIndex: 'blngCs',
      // },
      {
        title: '添加时间',
        dataIndex: 'creTime',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        render: text => moment(text).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        dataIndex: 'operate',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        render: (text, record) => (
          <Fragment>
            <Link to={`${tempUrl}/detail?refundInfoId=${record.refundInfoId}&type=1`}>查看</Link>
            {/* {Number(record.state) === 3 ? null : <Divider type="vertical" />} */}
            {this.renderMore(record)}
          </Fragment>
        ),
      },
    ];
    const accuColumns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeIdName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '返款金额',
        dataIndex: 'refundAmt',
        onCell: () => ({
          style: {
            textAlign: 'right',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'right',
          },
        }),
      },

      {
        title: '状态',
        dataIndex: 'stateName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      {
        title: '来源',
        dataIndex: 'sourceName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      {
        title: '所属客服',
        dataIndex: 'blngCs',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
      },
      // {
      //   title: '所属客服',
      //   dataIndex: 'blngCs',
      // },
      {
        title: '添加时间',
        dataIndex: 'creTime',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        render: text => moment(text).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        dataIndex: 'operate',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
            textAlign: 'center',
          },
        }),
        render: (text, record) => (
          <Fragment>
            <Link to={`${tempUrl}/detail?refundInfoId=${record.refundInfoId}&type=2`}>查看</Link>

            {this.renderMore(record)}
          </Fragment>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard}>
          <Tabs activeKey={activeKey} onChange={this.tabChange}>
            <TabPane tab="社保服务数据" key="1">
              <RebateTmp
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                onRef={this.onRef}
                loading={loading}
                data={pageData}
                columns={insColumns}
                rowKey="refundInfoId"
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                activeKey="1"
                getList={this.getList}
                location={location}
                serviceDicList={serviceDictList}
                clearSelect={this.clearSelect}
              />
            </TabPane>
            <TabPane tab="公积金服务数据" key="2">
              <RebateTmp
                selectedRows={selectedRows}
                selectedRowKeys={selectedRowKeys}
                onRef={this.onRef1}
                loading={loading}
                data={accuData}
                columns={accuColumns}
                rowKey="refundInfoId"
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                activeKey="2"
                getList={this.getList}
                location={location}
                serviceDicList={serviceDictList}
                clearSelect={this.clearSelect}
              />
            </TabPane>
          </Tabs>
          <UpdateModal
            title="修改"
            visible={updateVisible}
            onOk={this.updateHandleOk}
            onCancel={() => this.toggleUpdateModal(false)}
            data={Number(activeKey) === 1 ? insUpdateVo : accuUpdateVo}
          />
          {/* <Modal
            title="作废"
            visible={voidVisible}
            onOk={this.voidHandleOk}
            onCancel={() => this.toggleVoidModal(false)}
          >
            <div>将对当前数据进行作废，是否继续？</div>
          </Modal> */}
          <Modal
            title="取消作废"
            visible={cancelVoidVisible}
            onOk={this.cancelVoidHandleOk}
            onCancel={() => this.toggleCancelVoidModal(false)}
          >
            <div>将对当前数据进行取消作废，是否继续？</div>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Rebate;
